/*
 * @(#) PagerSqlExecutor.java 2010-9-6
 *
 * Copyright (c) 2010, Strong Technology. All Rights Reserved.
 * Strong Technology. CONFIDENTIAL
 */
package cn.strong.gweva.common.ibatisext;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.strong.gweva.common.integration.dao.Dialect;

import com.ibatis.sqlmap.engine.execution.SqlExecutor;
import com.ibatis.sqlmap.engine.mapping.statement.RowHandlerCallback;
import com.ibatis.sqlmap.engine.scope.StatementScope;


/**
 * 分页SQL执行类
 * 
 * @author lilanfei
 * @version 1.0
 * @since 2010-9-6
 */

public class PagerSqlExecutor extends SqlExecutor
{

	//日志
	private static final Log logger = LogFactory.getLog(PagerSqlExecutor.class);

	//修改SQK
	private Dialect dialect;
	//时候可以Limit
	private boolean enableLimit = true;

	/**
	 * @return Dialect取得
	 */
	public Dialect getDialect()
	{
		return dialect;
	}
	/**
	 * Dialect设定
	 * @param dialect 
	 */
	public void setDialect(Dialect dialect)
	{
		this.dialect = dialect;
	}
	/**
	 * @return enableLimit
	 */
	public boolean isEnableLimit()
	{
		return enableLimit;
	}
	/**
	 * 设定 enableLimit
	 * @param enableLimit
	 */
	public void setEnableLimit(boolean enableLimit)
	{
		this.enableLimit = enableLimit;
	}
	
	/**
	 * SQL执行
	 * @param request StatementScope
	 * @param conn 连接
	 * @param sql SQL
	 * @param parameters 参数
	 * @param skipResults 开始行号
	 * @param maxResults 最大检索行数
	 * @param callback 回调方法
	 */
	public void executeQuery(StatementScope request, Connection conn, String sql,
			Object[] parameters, int skipResults, int maxResults, RowHandlerCallback callback)
			throws SQLException
	{
		if ((skipResults != NO_SKIPPED_RESULTS || maxResults != NO_MAXIMUM_RESULTS)
				&& supportsLimit())
		{
			sql = dialect.getLimitString(sql, skipResults, maxResults);
			if (logger.isDebugEnabled())
			{
				logger.debug(sql);
			}
			skipResults = NO_SKIPPED_RESULTS;
			maxResults = NO_MAXIMUM_RESULTS;
		}
		super.executeQuery(request, conn, sql, parameters, skipResults, maxResults, callback);
	}

	/**
	 * 时候支持Limit
	 * @return
	 */
	public boolean supportsLimit()
	{
		if (enableLimit && dialect != null)
		{
			return dialect.supportsLimit();
		}
		return false;
	}

}
